package cn.aias.rbac.domain.model;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import jakarta.persistence.Version;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.Set;


@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = "roles") // Exclude Hibernate-managed collection
@Entity
@Table(name = "users", indexes = {
        // 单字段索引：username 字段（常用查询字段）
        @Index(name = "idx_users_username", columnList = "username"),
        // 单字段索引：email 字段（唯一且常用查询）
        @Index(name = "idx_users_email", columnList = "email"),
        // 新增 createOn 字段的索引（关键修改）
        @Index(name = "idx_users_create_time", columnList = "createTime")
})
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;    // 用户名（RBAC核心属性）
    private String ssoId;       // SSO关联ID
    private String password;    // 密码（实际需加密存储）
    private String email;       // 邮箱（可选）
    @Version
    private Integer version;

    // 创建时间（仅插入时赋值）
    @CreationTimestamp
    private LocalDateTime createTime;

    // 修改时间（每次更新时自动刷新）
    @UpdateTimestamp
    private LocalDateTime updateTime;

    // 用户-角色多对多关系（RBAC核心）
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roles;

}
